<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="65%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" @blur="checkExist" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="简称" prop="shortName">
            <el-input v-model="formData.shortName" placeholder="请输入简称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="合作模式" prop="cooperateMode">
            <el-select v-model="formData.cooperateMode" placeholder="请选择增值业务" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_EXPAND_PARTNER_COOPERATE_MODE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="合作区域" prop="cooperateArea">
            <el-cascader
              v-model="formData.cooperateArea"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              clearable
              filterable
              placeholder="合作区域"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="所在区域" prop="location">
            <el-cascader
              v-model="formData.location"
              :options="areaList"
              :props="defaultProps"
              class="w-1/1"
              clearable
              filterable
              placeholder="所在区域"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="行业分类" prop="tradeType">
            <el-select v-model="formData.tradeType" placeholder="请选择行业分类">
              <el-option-group
                v-for="group in IndustryTypeOptionsGroup"
                :key="group.label"
                :label="group.label"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用模式" prop="costMode">
            <el-input v-model="formData.costMode" placeholder="请输入费用模式" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="联系人" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入联系人" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="contactNumber">
            <el-input v-model="formData.contactNumber" placeholder="请输入联系方式" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="主推产品" prop="mainProduct">
            <el-input v-model="formData.mainProduct" placeholder="请输入主推产品" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {
  ExpandTargetPartnerApi,
  ExpandTargetPartner,
  IndustryTypeOptionsGroup
} from '@/api/biz/expand/targets/partner'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { defaultProps } from '@/utils/tree'
import * as AreaApi from '@/api/system/area'

/** 拓展目标_合作伙伴 表单 */
defineOptions({ name: 'ExpandTargetPartnerForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const areaList = ref([]) // 地区列表

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  shortName: undefined,
  cooperateMode: undefined,
  cooperateArea: undefined,
  location: undefined,
  address: undefined,
  tradeType: undefined,
  costMode: undefined,
  contactName: undefined,
  contactNumber: undefined,
  mainProduct: undefined,
  remark: undefined,
  ownerUserId: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const checkFlag = ref(0)

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得地区列表
  areaList.value = await AreaApi.getAreaTree()

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ExpandTargetPartnerApi.getExpandTargetPartner(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (checkFlag.value === 1) {
    message.error('合作伙伴已存在,请检查名称')
    return false
  }
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ExpandTargetPartner
    if (formType.value === 'create') {
      await ExpandTargetPartnerApi.createExpandTargetPartner(data)
      message.success(t('common.createSuccess'))
    } else {
      await ExpandTargetPartnerApi.updateExpandTargetPartner(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    shortName: undefined,
    cooperateMode: undefined,
    cooperateArea: undefined,
    location: undefined,
    address: undefined,
    tradeType: undefined,
    costMode: undefined,
    contactName: undefined,
    contactNumber: undefined,
    mainProduct: undefined,
    remark: undefined,
    ownerUserId: undefined
  }
  formRef.value?.resetFields()
  checkFlag.value = 0
}

const checkExist = async () => {
  checkFlag.value = await ExpandTargetPartnerApi.checkExistByName(formData.value.name)
  if (checkFlag.value === 1) {
    message.error('合作伙伴已存在,请检查名称')
  }
}
</script>
